<template>
  <div class="area-management-list">
    <el-card>
      <div slot="header" class="card-header">
        <span>区域管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加区域
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table v-loading="loading" :data="areaList" stripe style="width: 100%">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="areaName" label="区域名称" width="180"></el-table-column>
          <el-table-column prop="description" label="区域描述">
              <template slot-scope="scope">
                <el-popover placement="top" title="区域描述" width="400" trigger="hover">
                  <p>{{ scope.row.description }}</p>
                  <div slot="reference" class="description-tooltip">
                    <span>{{ scope.row.description && scope.row.description.length > 50 ? scope.row.description.substring(0, 50) + '...' : (scope.row.description || '-') }}</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            
            <el-table-column prop="ipRanges" label="IP范围">
              <template slot-scope="scope">
                <el-popover placement="top" title="IP范围" width="400" trigger="hover">
                  <div v-if="scope.row.ipRanges && JSON.parse(scope.row.ipRanges).length > 0">
                    <div v-for="(ip, index) in JSON.parse(scope.row.ipRanges)" :key="index" style="margin-bottom: 5px;">
                      {{ ip }}
                    </div>
                  </div>
                  <div v-else>-</div>
                  <div slot="reference" class="ip-ranges-tooltip">
                    <span v-if="scope.row.ipRanges && JSON.parse(scope.row.ipRanges).length > 0">
                      {{ JSON.parse(scope.row.ipRanges)[0] }}{{ JSON.parse(scope.row.ipRanges).length > 1 ? ' 等' + JSON.parse(scope.row.ipRanges).length + '个' : '' }}
                    </span>
                    <span v-else>-</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" :formatter="dateFormat"></el-table-column>
          <el-table-column label="设备数量" width="100" :formatter="deviceCountFormat"></el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-dropdown size="small">
                <el-button size="small" type="text">
                  <i class="el-icon-setting"></i> 操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleEdit(scope.row)">
                    <i class="el-icon-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleViewDevices(scope.row)">
                    <i class="el-icon-s-tools"></i> 查看设备
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="handleDelete(scope.row)">
                    <i class="el-icon-delete"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AreaManagementList',
  data() {
    return {
      areaList: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  methods: {
    // 获取区域列表
    getAreaList() {
      this.loading = true;
      this.$api.areaApi.getAll().then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        const areaData = data && data.data || [];
        this.areaList = areaData;
        this.total = areaData.length;
      }).catch(err => {
        console.error('获取区域列表失败:', err);
        this.$message.error('获取区域列表失败，请稍后重试');
        this.areaList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 添加区域
    handleAdd() {
      this.$router.push('/area-management/add');
    },
    
    // 编辑区域
    handleEdit(row) {
      this.$router.push({ path: '/area-management/edit/' + row.id });
    },
    
    // 查看设备
    handleViewDevices(row) {
      this.$router.push({ path: '/device-management?areaId=' + row.id });
    },
    
    // 删除区域
    handleDelete(row) {
      this.$confirm('确定要删除这个区域吗？删除后该区域下的所有设备也将被删除。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            this.$api.areaApi.delete(row.id).then(data => {
              this.$message.success('删除成功');
              this.getAreaList(); // 重新加载列表
            }).catch(err => {
          console.error('删除区域失败:', err);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 刷新列表
    handleRefresh() {
      this.getAreaList();
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getAreaList();
    },
    
    // 当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getAreaList();
    },
    
    // 日期格式化
    dateFormat(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        return date.toLocaleString('zh-CN');
      }
      return '';
    },
    
    // 设备数量格式化
    deviceCountFormat(row) {
      return row.deviceCount || 0;
    }
  },
  mounted() {
    // 页面加载时获取区域列表
    this.getAreaList();
  }
};
</script>

<style scoped>
.area-management-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
}

.table-container {
  margin-top: 20px;
}

.description-tooltip,
.ip-ranges-tooltip {
  cursor: pointer;
  color: #409eff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>